using System;
using ScenarioFramework.Modules.PCM.DataModel.ConfigurationManager.Entity;
using System.Threading;

namespace ScenarioFramework.Modules.PCM.DataModel.ConfigurationManager.Entity
{
	/// <summary>
	/// Summary description for MetaWorkflowHelper.
	/// </summary>
	public class XMLEntitiesHelper
	{
		static System.Threading.Mutex instanceMutex = new System.Threading.Mutex();

		static XMLEntities xmlEntities = null;
		static XMLEntities xmlEntitiesClone = null;
		
		public XMLEntitiesHelper()
		{
		}

		public static void LoadConfiguragion()
		{
			instanceMutex.WaitOne();
			if ( xmlEntities ==  null)
			{
				xmlEntities = new XMLEntities();
				xmlEntities.ReadFromConfiguration();
				xmlEntitiesClone = xmlEntities;
			}
			instanceMutex.ReleaseMutex();
		}

		public static XMLEntities XMLEntities()
		{
			return xmlEntitiesClone;
		}

		public static XMLEntityAttribute GetEntityAttribute(string sEntityName, string sAttributeName)
		{
			XMLEntity entity = null;
			XMLEntityAttribute attribute = null;

			try
			{
				entity = xmlEntitiesClone.GetById (sEntityName);
			}
			catch ( ScenarioFramework.Modules.PCM.DataModel.ConfigurationManager.Exception.EntityNotFound)
			{
				return null;
			}

			try
			{
				attribute = entity.XMLEntityAttributes.Get(sAttributeName);
			}
			catch ( ScenarioFramework.Modules.PCM.DataModel.ConfigurationManager.Exception.EntityAttributeNotFound) 
			{
				return null;
			}

			return attribute;
		}


		public static XMLEntityAttribute GetEntityAttribute(string sEntityAttribute)
		{
			string sEntity = string.Empty;
			string sAttribute = string.Empty;

			XMLEntitiesHelper.GetEntityAndAttribute ( sEntityAttribute, ref sEntity, ref sAttribute);

			return XMLEntitiesHelper.GetEntityAttribute (sEntity, sAttribute);
		}




		public static void GetEntityAndAttribute(string Name, ref string EntityName, ref string AttributeName)
		{
			// extract position of "." and Entity - Attribute names 
			int IDX = Name.IndexOf(".",0);
			if (IDX <= 0)
			{
				EntityName= Name;
				AttributeName = string.Empty;
			}
			else
			{
				EntityName = Name.Substring(0,(IDX));
				AttributeName = Name.Substring(IDX+1);
			}
		}
	}
}
